package com.suian.service.impl;

import com.suian.aspect.RequestAspect;
import com.suian.dao.ProductInfo;
import com.suian.mapper.ProductMapper;
import com.suian.service.ProductService;
import io.github.resilience4j.circuitbreaker.annotation.CircuitBreaker;
import org.apache.ibatis.session.SqlSession;
import org.mybatis.spring.SqlSessionTemplate;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

@Service
public class ProductServiceImpl implements ProductService {
    private static final Logger log = LoggerFactory.getLogger(ProductServiceImpl.class);
    @Autowired
    private ProductMapper productMapper;
    @Autowired
    private SqlSessionTemplate sqlSessionTemplate;

    @CircuitBreaker(name = "productServiceImpl", fallbackMethod = "fallbackGetProduct")
    @Override
    public ProductInfo selectProductById(Integer productId) {
        // 模拟远程服务调用（可能失败）
        if (Math.random() > 0.5) {
            throw new RuntimeException("Service Error");
        }
        return productMapper.selectProductById(productId);
    }

    public void testSqlSessionTemplate() {
        SqlSession sqlSession = sqlSessionTemplate.getSqlSessionFactory().openSession();
    }

    //降级方法
    public ProductInfo fallbackGetProduct(Integer productId,Throwable ex) {
        log.error("熔断器触发 productId: {}, Error: {}", productId, ex.getMessage());
        // 返回默认值或缓存数据
        return new ProductInfo();
    }
}
